package net.sf.ivyide.idea;

import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class IntellijUtil {

    public static void execute(final Runnable r, final ProgressIndicator progress) {
        Application application = ApplicationManager.getApplication();
        try {
            Method method = application.getClass().getMethod("executeOnPooledThread", Runnable.class);
            method.invoke(application, r);
        } catch (NoSuchMethodException e) {
            //intellij 5..
            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        ProgressManager.getInstance().runProcess(r, progress);
                    } catch (ProcessCanceledException processcanceledexception) {
                    }
                }
            });
            t.start();
            //r.run();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getBaseDir(final Project project) {
        try {
            Method method = project.getClass().getMethod("getBaseDir");
            Object basedir = method.invoke(project);
            method = basedir.getClass().getMethod("getPath");
            return (String) method.invoke(basedir);
        } catch (NoSuchMethodException e) {
            //try the intellij 5 approach...
            return ProgressUtilities.executeAsReadAction(new ProgressAwareCallable<String>() {
                public String call(ProgressIndicator indicator) throws Exception {
                    return project.getProjectFile().getParent().getPath();
                }
            }, null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
}
